<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname,user_type';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                if($v["user_type"] == 0){
                    $v->user_type = "客户";
                }else if($v["user_type"] == 1){
                    $v->user_type = "分公司";
                }else if($v["user_type"] == 2){
                    $v->user_type = "代理商";
                }else if($v["user_type"] == 3){
                    $v->user_type = "销售";
                }

                //上级用户姓名
                $v->pid_name = Db::name("user")->field("nickname")->where("id = " . $v->pid)->find()["nickname"] ?? "";
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $params = $this->request->post('row/a');
        
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);

            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            
            $lists = [];
            if($row["user_type"] == 0){
                $lists =  Db::name("user")
                ->field("id, nickname, user_type")
                ->where("user_type = 3")
                ->select();
            }
            if($row["user_type"] == 3){
                $lists =  Db::name("user")
                ->field("id, nickname, user_type")
                ->where("user_type = 2")
                ->select();
            }
            if($row["user_type"] == 2){
                $lists =  Db::name("user")
                ->field("id, nickname, user_type")
                ->where("user_type = 1")
                ->select();
            }

            foreach($lists as $key => $value){
                $user_type = Db::name("user")
                ->field("user_type")
                ->where("id = " . $value["id"])
                ->find();

                if($user_type["user_type"] == 1){
                    $lists[$key]["nickname"] = "分公司-" . $value["nickname"];
                }

                if($user_type["user_type"] == 2){
                    $lists[$key]["nickname"] = "代理商-" . $value["nickname"];
                }

                if($user_type["user_type"] == 3){
                    $lists[$key]["nickname"] = "销售-" . $value["nickname"];
                }
            }

            $lists = array_column($lists, "nickname", "id");

            $this->assign("pidList", $lists);

            // $this->view->assign('pidList', build_select('row[pid]',$lists , $row['pid'], ['class' => 'form-control selectpicker']));

            return $this->view->fetch();
        }

        //判断当前用户角色是否有变更，如果有变更，是否有其他用户是下级，如果有，则禁止修改
        if($row["user_type"] != $params["user_type"]){
            $nextUser = Db::name("user")
            ->where("pid = " . $row["id"])
            ->find();
            if($nextUser){
                $this->error(__('修改角色失败，您还有下级用户未处理', ''));
            }
        }

        //普通客户是否选择了销售
        if($params["user_type"] == 0){
            //查询当前系统中是否有销售
            $is_have_sale = Db::name("user")
            ->where("user_type = 3")
            ->find();

            if(!$params["pid"] && $is_have_sale){
                $this->error("请选择上级销售");
            }
            
            if($params["pid"] && !empty($params["pid"])){
                $is_sale = Db::name("user")
                ->where("id = " . $params["pid"])
                ->find();
                if($is_sale["user_type"] != 3){
                    $this->error("您选择的上级不是销售，请重新选择");
                }
            }
            
        }

        //如果客户直接改编为分公司角色，则清除当前的pid
        if($params["user_type"] == 1){
            $params["pid"] = 0;
        }

        //角色变更为代理商时，检测上级是否是分公司
        if($params["user_type"] == 2){
            //查询当前系统中是否有分公司
            $is_have_branch = Db::name("user")
            ->where("user_type = 1")
            ->find();

            if(!$params["pid"] && $is_have_branch){
                $this->error("请选择上级分公司");
            }

            if($params["pid"] && !empty($params["pid"])){
                $is_branch_office = Db::name("user")
                ->where("id = " . $params["pid"])
                ->find();
                if($is_branch_office["user_type"] != 1){
                    $this->error("您选择的上级不是分公司，请重新选择");
                }
            }
            
        }

        //角色变更为销售时，检测上级是否是代理商
        if($params["user_type"] == 3){
            //查询当前系统中是否有代理商
            $is_have_agent = Db::name("user")
            ->where("user_type = 2")
            ->find();

            if(!$params["pid"] && $is_have_agent){
                $this->error("请选择上级代理商");
            }

            if($params["pid"] && !empty($params["pid"])){
                $is_agent = Db::name("user")
                ->where("id = " . $params["pid"])
                ->find();
                if($is_agent["user_type"] != 2){
                    $this->error("您选择的上级不是代理商，请重新选择");
                }
            }
            
        }
        
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //获取上一个等级的用户列表
    public function getUserPidLists()
    {
        $user_type = input("user_type");
        $id = input("id");

        //获取当前用户信息
        $row = $this->model->get($id);

        if($user_type == 0){
            $lists =  Db::name("user")
            ->field("id, nickname, user_type")
            ->where("user_type = 3")
            ->select();
        }
        if($user_type == 3){
            $lists =  Db::name("user")
            ->field("id, nickname, user_type")
            ->where("user_type = 2")
            ->select();
        }
        if($user_type == 2){
            $lists =  Db::name("user")
            ->field("id, nickname, user_type")
            ->where("user_type = 1")
            ->select();
        }

        foreach($lists as $key => $value){
            $user_type = Db::name("user")
            ->field("user_type")
            ->where("id = " . $value["id"])
            ->find();

            if($user_type["user_type"] == 1){
                $lists[$key]["nickname"] = "分公司-" . $value["nickname"];
            }

            if($user_type["user_type"] == 2){
                $lists[$key]["nickname"] = "代理商-" . $value["nickname"];
            }

            if($user_type["user_type"] == 3){
                $lists[$key]["nickname"] = "销售-" . $value["nickname"];
            }
        }

        $lists = array_column($lists, "nickname", "id");

        // $html = build_select('row[pid]',$lists , $row["pid"], ['class' => 'form-control selectpicker']);

        return json(["lists" => $lists]);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //查询是否有下级，有的话，不允许删除
        $nextUser = Db::name("user")
        ->where("pid = " . $row["id"])
        ->find();
        if($nextUser){
            $this->error("有下级用户，禁止删除");
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    //导出数据
    public function export()
    {
        set_time_limit(0);//设置时间限制
        $ids = $this->request->post('ids'); //获取数据的所有id

        //导出的字段
        $field = [
            'nickname',
            'mobile',
            'user_type',
            'service_labels_name',
            'parent>nickname',
            'gender',
            'desc',
            'email',
            'bio',
            'score',
            'birthday',
            'money',
            'logintime',
            'createtime'
        ];
        //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
        $fieldComment = [
            'parent>nickname' => '上级用户昵称',
        ];
        $fields = $this->getField($field, "user");

        $objPHPExcel = new Spreadsheet();
        $firstChar = 65;
        $tempChar = '';
        $tempCharNum = '';
        foreach ($fields as $key => &$field) {
            //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
            if ($firstChar > 90) {
                $firstChar = 65; //当超出 Z 时，重新跳到 A 开始

                if ($tempChar == '') {
                    $tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
                } else {
                    $tempCharNum += 1;
                }
                $tempChar = chr($tempCharNum);
            }
            $column = chr($firstChar);
            $firstChar++;

            $char = $tempChar . $column; //哪一列

            //处理连表的导出字段
            if (is_numeric($field)) {
                $field = [
                    'field' => $key,
                    'comment' => $fieldComment[$key],
                    'type' => 'varchar',
                    'chose' => [],
                ];
            }
            $field['char'] = $char;//记录哪一列，数据循环时可直接取用
            //设置表头
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
            //改变长度
            $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
        }


        //查询数据
        $wheres = [
        
        ];
        if ($ids != 'all' && !empty($ids)) {
            $wheres['user.id'] = ['in', $ids];
        }
        $list = $this->model
            ->with(['parent'])
            ->where($wheres)
            ->select();

        //输出表格
        foreach ($list as $key => &$val) {
            $val = $val->toArray();
            $i = $key + 2;//表格是从2开始的,第1行为表头
            foreach ($fields as &$field) {
                $data = $val[$field['field']] ?? '';
                
                //连表显示的字段
                if (strpos($field['field'], '>') !== false) {
                    $fieldArr = explode('>', $field['field']);
                    $data = $val[$fieldArr[0]][$fieldArr[1]];
                }
                //转换为时间格式
                if (is_numeric($data) && mb_strlen($data) == 10) {
                    $data = date('Y-m-d H:i:s', $data);
                }
                //将选择项转换成对应的值
                if (!empty($field['chose'])) {
                    $data = $field['chose'][$data];
                }
                //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
                if (strpos($field['type'], 'char') !== false) {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
                }
            }
        }

        $outputFileName = date("YmdHis") . '导出.xls';

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;
    }

}
